package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.mapper.MenuMapper;
import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.Menu;
import com.csdj.server.pojo.Salary;
import com.csdj.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyx
 * @since 2022-12-12
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired(required = false)
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Menu> getMenusByAdminId() {
        // id 通过 Security 全局对象 拿到 传到 dao层
        Integer id = ((Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        //从redis 获取数据
        List<Menu> menus = (List<Menu>) ops.get("menu_" + id);
        //如果 从 redis中拿到的数据是空的
        if(CollectionUtils.isEmpty(menus)){
            //那就去mysql数据库中查
            menus = menuMapper.getMenusByAdminId(id);
            //在 存到 redis 中
            ops.set("menus_"+id,menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getAllMenuWithRole() {

        return menuMapper.getAllMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
